package art.java.concurrency.chapter04;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @author <a href="eric_zheng@lanzuo.com.cn">eric</a>
 * @version 1.0.0
 * Description: 管道输入/ 输出流
 */
public class Piped {

    public static void main(String[] args) throws IOException {
        // 输出流
        PipedWriter pipedWriter = new PipedWriter();
        // 输入流
        PipedReader pipedReader = new PipedReader();
        // 连接输入输出流
        try {
            pipedWriter.connect(pipedReader);
            Thread printThread = new Thread(new Print(pipedReader), "printThread");
            printThread.start();

            int receive = 0;
            while ((receive = System.in.read()) != -1) {
                pipedWriter.write(receive);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pipedWriter.close();
        }
    }

    public static class Print implements Runnable {

        private PipedReader in;

        public Print(PipedReader in) {
            this.in = in;
        }

        @Override
        public void run() {
            int receive = 0;

            try {
                while (true) {
                    if (((receive = in.read()) != -1)) {
                        System.out.println((char) receive);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
